package cn.com.cetccst.dataupload.sync.compliance;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.work.Data;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import com.google.gson.Gson;

import org.json.JSONObject;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.cetccst.datacenter.policy.PolicyRepository;
import cn.com.cetccst.datacenter.policy.entity.ComplianceRecordEntity;
import cn.com.cetccst.dataupload.network.DataUploadHttpRequester;
import cn.com.cetccst.tools.log.CommonLogger;
import retrofit2.Response;

public class UploadComplianceWorker extends Worker {

    private static final String CMD_NAME = "commands.DeviceComplianceStatusCmd";
    public final static String DATA_LATEST_DATE = "data_latest_date";

    public UploadComplianceWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {

        long date = getInputData().getLong(DATA_LATEST_DATE, 0);
        CommonLogger.info("upload the compliance data in " + new Date(date));
        //加急工作的兼容性处理（没有验证）
//        setForegroundAsync(getForegroundInfo());

        List<ComplianceRecordEntity> records = PolicyRepository.getInstance().getComplianceRecordsByDate(date);
        try {
            Response<JSONObject> response = DataUploadHttpRequester.getInstance().requestUploadData(CMD_NAME, buildPayload(date, records));
            if (response == null || !response.isSuccessful())
                return Result.retry();
        } catch (IOException e) {
            CommonLogger.error("begin to upload upload compliance records error", e);
            return Result.retry();
        }
        PolicyRepository.getInstance().deleteComplianceRecordsByDate(date);
        return Result.success();
    }

    private String buildPayload(long date, List<ComplianceRecordEntity> records) {
        Map<String, Object> statusBody = new HashMap<>();
        Map<String, Object> reason = new HashMap<>();

        for (ComplianceRecordEntity entity : records) {
            statusBody.put(entity.getKey(), entity.getStatus());
//            机卡分离的原因没持久化，暂不处理
//            if ("deviceBindingStatus".equals(entity.getKey())) {
//                reason.put("deviceBinding", 1);
//            }
        }
//        statusBody.put("reason", reason);
        statusBody.put("time", date);
        return new Gson().toJson(statusBody);
    }
}
